﻿//
// Copyright (c) 2011 HyperCrunch, Inc. http://www.hypercrunch.com 
// Author: Nik Kalyani  http://www.kalyani.com (Twitter: @techbubble)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Framework;
using DotNetNuke.Services.Search;
using DotNetNuke.UI;

using DotNetNuke.Entities.Content.Common;
using DotNetNuke.Entities.Content.Taxonomy;
using DotNetNuke.Entities.Content;
using RazorEngine;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace HyperCrunch.Druid.Mobile
{
    /// <summary>
    /// Renders a mobile view of a DotNetNuke portal using jQuery Mobile
    /// </summary>
    /// 
  
    public class AppRenderer : IContentRenderer
    {
        public ActionResult RenderContent(UIContext uiContext)
        {
            // Try and get a module instance from the "auid" querystring
            ModuleInfo moduleInfo = null;
            try
            {
                if (uiContext.Context.Request.QueryString[Globals.MOBILE_APP_UNIQUEID_PARAMETER] != null)
                {
                    string auid = uiContext.Context.Request.QueryString[Globals.MOBILE_APP_UNIQUEID_PARAMETER];
                    moduleInfo = GetModuleFromAUID(auid);
                }
            }
            catch
            {
                moduleInfo = null;
            }

            if (moduleInfo == null)
            {
                try
                {
                    if (uiContext.JsonSettings.ContainsKey("appRenderer"))
                    {
                        Dictionary<string, object> settings = (Dictionary<string, object>)uiContext.JsonSettings["appRenderer"];
                        if (settings.ContainsKey(Globals.MOBILE_APP_UNIQUEID_PARAMETER))
                        {
                            string auid = settings[Globals.MOBILE_APP_UNIQUEID_PARAMETER].ToString();
                            moduleInfo = GetModuleFromAUID(auid);
                        }
                    }
                }
                catch
                {
                    moduleInfo = null;
                }
            }

            // If we can't get a valid module, we'll report the error and end processing
            if (moduleInfo == null)
                return new ContentResult
                {
                    Content = Utility.ErrorHtmlPage("Error displaying the requested application because a valid Application Unique Identifier (\"auid\") was not present in the URL")
                };

            ModuleMetaInfo moduleMetaInfo = ModuleMetaInfo.Instance(moduleInfo, uiContext);
            object bizController = Utility.GetModuleBusinessController(moduleInfo);
            if (Utility.IsMobileRenderable(moduleInfo, moduleMetaInfo, uiContext))
                return GetAppContent(uiContext, moduleInfo, moduleMetaInfo, bizController, "");
            else
                return GetAppSearchContent(moduleInfo, uiContext, bizController);
        }

        public static ModuleInfo GetModuleFromAUID(string auid)
        {
            string[] moduleInfoFrags = auid.Split(Globals.MOBILE_APP_UNIQUEID_SEPARATOR.ToCharArray());
            int tabId = Convert.ToInt32(moduleInfoFrags[0]);
            int moduleId = Convert.ToInt32(moduleInfoFrags[1]);
            ModuleController moduleController = new ModuleController();
            return moduleController.GetModule(moduleId, tabId);
        }

        public static ActionResult GetAppSearchContent(ModuleInfo moduleInfo,UIContext uiContext, object bizController)
        {
            var searchableBusinessController = bizController as ISearchable;
            if (searchableBusinessController == null)
            {
                return new ContentResult { Content = string.Empty };
            }

            string content;
            SearchItemInfoCollection itemCollection = searchableBusinessController.GetSearchItems(moduleInfo);
            if (itemCollection.Count == 0)
            {
                content = "No content";
                //  title = moduleInfo.ModuleTitle ?? "";
            }
            else if (itemCollection.Count == 1)
            {
                content = itemCollection[0].Content;
                // title = moduleInfo.ModuleTitle ?? "";
            }
            else
            {
                StringBuilder moduleContent = new StringBuilder();
                //   isList = true;
                foreach (SearchItemInfo itemInfo in itemCollection)
                {
                    moduleContent.Append("<li>" + itemInfo.Content + "</li>");
                }
                content = moduleContent.ToString();
            }

            return new ContentResult { Content = content };
        }

        /// <summary>
        /// Renders the contents of a View defined in a Razor script file
        /// Also, dynamically compiles Controller and ViewModel code and passes
        /// ViewModel intance to the View for rendering
        /// </summary>
        /// <param name="uiContext"></param>
        /// <param name="moduleInfo"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public static ActionResult GetAppContent(UIContext uiContext, ModuleInfo moduleInfo, ModuleMetaInfo moduleMetaInfo, object bizController, string returnUrl)
        {
            if (!File.Exists(moduleMetaInfo.AppViewFile))
                return new ContentResult { Content = Utility.ErrorHtmlPage("Required script \"" + moduleMetaInfo.ModuleFolder + "/" + Globals.RAZOR_MOBILE_FOLDER + "/" + Globals.RAZOR_MOBILE_APP_SCRIPT + "\" was not found") };

            IMobileAppController appControllerInstance = null;
            Assembly assembly = null;
            bool hasAssembly = false;

            // Check the standard business controller assembly to see if "AppController" is defined
            // If it exists, try to instantiate an instance of AppController
            if (bizController != null)
            {
                assembly = bizController.GetType().Assembly;
                Type appControllerType = assembly.GetType(bizController.GetType().Namespace + ".AppController");
                if (appControllerType != null)
                    appControllerInstance = (IMobileAppController)Activator.CreateInstance(appControllerType);

            }
            // Could not instantiate AppController from standard business controller, so try and
            // compile dynamically from "mobile" sub-folder
            if (appControllerInstance == null)
            {
                assembly = null;
                if (!File.Exists(moduleMetaInfo.AssemblyFile))
                    hasAssembly = BuildAssembly(uiContext, moduleMetaInfo);
                else
                {
                    assembly = Assembly.LoadFrom(moduleMetaInfo.AssemblyFile);
                    IList<CustomAttributeData> customAttributes = assembly.GetCustomAttributesData();

                    object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                    long controllerTicks = 0;
                    long modelTicks = 0;
                    if (attributes.Length > 0)
                    {
                        string description = ((AssemblyDescriptionAttribute)attributes[0]).Description;
                        string[] frags = description.Split(';');
                        controllerTicks = Convert.ToInt64(frags[0]);
                        modelTicks = Convert.ToInt64(frags[1]);
                    }
                    if ((controllerTicks < File.GetLastWriteTimeUtc(moduleMetaInfo.AppControllerFile).Ticks) ||
                        (modelTicks < File.GetLastWriteTimeUtc(moduleMetaInfo.AppModelFile).Ticks))
                    {
                        assembly = null;
                        hasAssembly = BuildAssembly(uiContext, moduleMetaInfo);
                    }
                    else
                        hasAssembly = true;
                }

                if (hasAssembly)
                {
                    if (assembly == null)
                        assembly = Assembly.LoadFrom(moduleMetaInfo.AssemblyFile);

                    appControllerInstance = (IMobileAppController)GetAppControllerInstance(assembly, moduleMetaInfo);
                }
            }

            if (appControllerInstance != null)
            {
                if (uiContext.Context.Request.QueryString[Globals.MOBILE_ROUTE_PARAMETER] != null)
                    return appControllerInstance.HandleRequest(moduleInfo, uiContext);
                else
                {

                    IMobileAppModel model = appControllerInstance.GetViewModel(moduleInfo, uiContext, returnUrl);
                    if (model != null)
                    {
                        if (File.Exists(moduleMetaInfo.AppStylesheetFile))
                            model.Stylesheet = moduleMetaInfo.MobileUrl + Globals.RAZOR_MOBILE_APP_STYLESHEET;

                        if (File.Exists(moduleMetaInfo.AppScriptFile))
                            model.Script = moduleMetaInfo.MobileUrl + Globals.RAZOR_MOBILE_APP_SCRIPT;
                    }
                    return new ContentResult { Content = Razor.Parse(File.ReadAllText(moduleMetaInfo.AppViewFile), model) };
                }
            }
            else
                return new ContentResult { Content = Utility.ErrorHtmlPage("Error: Could not find a controller to display the requested view") };

            
        }

        private static bool BuildAssembly(UIContext uiContext, ModuleMetaInfo moduleMetaInfo)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters options = new CompilerParameters { 
                GenerateExecutable = false, 
                OutputAssembly = moduleMetaInfo.AssemblyFile,
                TreatWarningsAsErrors = false                 
            };

            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Web.dll");
            options.ReferencedAssemblies.Add("System.XML.dll");
            options.ReferencedAssemblies.Add("System.Data.Linq.dll");
            options.ReferencedAssemblies.Add(uiContext.Context.Server.MapPath("~/bin/DotNetNuke.dll"));
            options.ReferencedAssemblies.Add(uiContext.Context.Server.MapPath("~/bin/HyperCrunch.Druid.dll"));
            options.ReferencedAssemblies.Add(uiContext.Context.Server.MapPath("~/bin/HyperCrunch.Druid.Mobile.dll"));

            // Add an assembly reference for what is presumably the module's primary assembly
            string moduleAssemblyPath = uiContext.Context.Server.MapPath("~/bin/" + moduleMetaInfo.AssemblyNamespace + ".dll");
            if (File.Exists(moduleAssemblyPath))
                options.ReferencedAssemblies.Add(moduleAssemblyPath);

            // Check if ~/bin/Modules exists and if not create it
            if (!Directory.Exists(moduleMetaInfo.AssemblyFolder)) Directory.CreateDirectory(moduleMetaInfo.AssemblyFolder);
            if (File.Exists(moduleMetaInfo.AssemblyInfoFile)) File.Delete(moduleMetaInfo.AssemblyInfoFile);
            if (File.Exists(moduleMetaInfo.LogFile)) File.Delete(moduleMetaInfo.LogFile);

            // We use the AssemblyDescription attribute to store information that allows detection
            // of changes in the model or controller file so the assembly can be recompiled
            File.WriteAllText(moduleMetaInfo.AssemblyInfoFile, 
                "using System.Reflection;\n" +
                "[assembly: AssemblyDescription(\"" +
                    File.GetLastWriteTimeUtc(moduleMetaInfo.AppControllerFile).Ticks.ToString() + ";" + 
                    File.GetLastWriteTimeUtc(moduleMetaInfo.AppModelFile).Ticks.ToString() + 
                 "\")]");

            CompilerResults results = codeProvider.CompileAssemblyFromFile(options, new string[]{ moduleMetaInfo.AssemblyInfoFile, moduleMetaInfo.AppControllerFile, moduleMetaInfo.AppModelFile });

            if (File.Exists(moduleMetaInfo.AssemblyInfoFile)) File.Delete(moduleMetaInfo.AssemblyInfoFile);

            if (results.Errors.Count > 0)
            {
                if (File.Exists(moduleMetaInfo.AssemblyFile)) File.Delete(moduleMetaInfo.AssemblyFile);
                StringBuilder errors = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                    errors.Append(error.FileName + "(" + error.Line.ToString() + "): " + error.ErrorText + "\n\n");
                File.WriteAllText(moduleMetaInfo.LogFile, errors.ToString());
                return false;
            }
            else
                return true;
        }

        private static IMobileAppController GetAppControllerInstance(Assembly assembly, ModuleMetaInfo moduleMetaInfo)
        {
            IMobileAppController appControllerInstance = null;
            string appControllerTypeName = moduleMetaInfo.AssemblyNamespace + ".AppController";

            Type appControllerType = assembly.GetType(appControllerTypeName);
            if (appControllerType != null)
                appControllerInstance = (IMobileAppController) Activator.CreateInstance(appControllerType);
            return appControllerInstance;
        }

    }
}
